package com.bjpowernode.mvc.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bjpowernode.common.client.RedisClient;
import com.bjpowernode.common.constant.AppConstants;
import com.bjpowernode.common.constant.RedisKey;
import com.bjpowernode.common.enums.RespCode;
import com.bjpowernode.mvc.config.SmsConfig;
import com.bjpowernode.mvc.service.inter.SmsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class SmsServiceImpl implements SmsService {

    private final SmsConfig smsConfig;
    private final RedisClient redisClient;

    //发送短信验证码
    @Override
    public String sendSms(String action, String phone) {

        //准备发送短信所需要的基础数据

        //1、验证码 4位数字 使用Random实现
        String code = RandomUtil.randomNumbers(4);
        System.out.println("【动力财富】你的验证码是：" + code + "，3分钟内有效！");

        //2、格式化短信内容
        String content = "";
        String codeKey = "";
        if (AppConstants.ACTION_LOGIN.equals(action)) {
            //登录
            codeKey = RedisKey.SMS_CODE_LOGIN + phone + ":" + code;
            content = String.format(smsConfig.getLoginContent(), code);
        } else if (AppConstants.ACTION_REGISTER.equals(action)) {
            //注册
            codeKey = RedisKey.SMS_CODE_REGISTER + phone + ":" + code;
            content = String.format(smsConfig.getRegisterContent(), code);
            //content = "【创信】你的验证码是：5873，3分钟内有效！";
        }

        //3.调用方法发送短信
        boolean isSave = false;
        boolean isSendOK = execSendSms(phone, content);
        if (isSendOK) {
            //4、存储验证内容到redis，有效时间3分钟
            //key需要与手机号相关，来判断这个验证码属于哪个手机号
            isSave = redisClient.setVal(codeKey, code, 3, TimeUnit.MINUTES);
        }


        return isSave ? RespCode.OK.name() : RespCode.FAIL.name();
    }

    /**
     * 删除短信验证码
     *
     * @param key
     */
    @Override
    public void removeSmsCode(String key) {
        redisClient.deleteKey(key);
    }

    //用来执行第三方接口   手机号、发送的内容
    private boolean execSendSms(String phone, String content) {

        boolean isSendOk = false;

        String host = smsConfig.getHost();
        String path = smsConfig.getPath();
        String method = "POST";
        String appcode = smsConfig.getAppCode();
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<>();
        querys.put("content", content);
        querys.put("mobile", phone);
        Map<String, String> bodys = new HashMap<>();


        try {
            //HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取response的body

            //检查HTTP响应的状态码是否为200(成功)
            //if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //String body = EntityUtils.toString(response.getEntity());
            String body = "{\n" +
                    "  \"ReturnStatus\": \"Success\",\n" +
                    "  \"Message\": \"ok\",\n" +
                    "  \"RemainPoint\": 420842,\n" +
                    "  \"TaskID\": 18424321,\n" +
                    "  \"SuccessCounts\": 1\n" +
                    "}";

            //解析json字符串
            //hutool工具类   isNotBlank()  判断是否不为空
            if (StrUtil.isNotBlank(body)) {
                //JSONObject实际上是一个Map，key  value
                JSONObject result = JSONUtil.parseObj(body);

                //读取ReturnStatus的值
                if ("SUCCESS".equalsIgnoreCase(result.getStr("ReturnStatus"))) {
                    isSendOk = true;
                }
            }
            //}


        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSendOk;
    }
}
